package indi.lddsdu.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.sun.org.apache.regexp.internal.RE;
import indi.lddsdu.bean.Record;
import indi.lddsdu.exception.RecordException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by jack on 18/6/10.
 */
public class DButil {

    private static Logger logger = LoggerFactory.getLogger(DButil.class);
    private static ComboPooledDataSource dataSource=new ComboPooledDataSource("mysql");

    private static Connection getConnection() throws SQLException {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            logger.warn("error ",e);
            throw e;
        }
    }

    static String sql_template = "select contentType, filePath, title, url from Record limit ?,?";

    /**
     * 从数据库中分段查询获取到record,用来构建索引
     * @param startIndex
     * @param totalNum
     * @return
     * @throws SQLException
     * @throws RecordException
     */
    public static List<Record> listRecords(int startIndex, int totalNum) throws SQLException, RecordException {
        Connection connection =  getConnection();
        PreparedStatement preparedStatement =connection.prepareStatement(sql_template);
        preparedStatement.setInt(1, startIndex);
        preparedStatement.setInt(2, totalNum);
        ResultSet resultSet = preparedStatement.executeQuery();
        //contentType | filePath | title  | url
        List<Record> recordList = new ArrayList<>();
        while (resultSet.next()){
            String contentType = resultSet.getString("contentType");
            String filePath = resultSet.getString("filePath");
            String title = resultSet.getString("title");
            String url = resultSet.getString("url");
            recordList.add(new Record(contentType, filePath, title, url));
        }
        connection.close();
        return recordList;
    }

}
